//
//  LLHomeViewController.swift
//  WeiBoShiBing
//
//  Created by Bingo on 15/10/27.
//  Copyright © 2015年 Bingo. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

enum LLStatusCellIdentifier:String{
    
    case NormalCell = "NormalCell"
    case ForwardCell = "ForwardCell"
    
}


class LLHomeViewController: LLBaseTableViewController {
    private var statuses:[LLStatus]?{
        didSet{
            tableView.reloadData()
        }
        
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        
        if !LLUserAccount.userLogin(){
            return
        }
        
        setUpNavgationBar()
        prepareTableView()
        //        loadData()
        
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
//        tableView.allowsSelection = false
       
        
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "SelectedPicture:", name: LLStatusPictureViewCellSelectedPictureNotification, object: nil)
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "popoverDismiss", name: "PopoverDismiss", object: nil)
        //加载微博数据
        
    }
    
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    func popoverDismiss(){
    
        let button = navigationItem.titleView as! UIButton
        homeTitleClick(button)
    }
    
    func SelectedPicture(notification:NSNotification){
        
//        print("picture点击事件")
//        LLStatusPictureViewCellSelectedPictureURLKey
        guard let models = notification.userInfo?[LLStatusPictureViewCellSelectedPictureModelKey] as? [LLPhotoBrowserModel]
            else{
                print("models有问题")
                return
        }
        
        guard let index = notification.userInfo?[LLStatusPictureViewCellSelectedPictureIndexKey] as? Int
            else{
                print("index有问题")
                return
        }
//        print("-------------\(urls)")
        let controller = LLPhotoBrowserViewController(models: models, selectedIndex: index)
        
        controller.transitioningDelegate = controller
        
        controller.modalPresentationStyle = UIModalPresentationStyle.Custom
    
        presentViewController(controller, animated: true, completion: nil)
    }
    
    func loadData(){
        print("加载微博数据")
        
        var since_id = statuses?.first?.id ?? 0
        var max_id = 0
        
        if pullUpView.isAnimating(){
            
            since_id = 0
            max_id = statuses?.last?.id ?? 0
            
        }
        LLStatus.loadStatus(since_id,max_id: max_id) { (statuses, error) -> () in
            
            self.refreshControl?.endRefreshing()
            
            self.pullUpView.stopAnimating()
            
            if error != nil{
                
                SVProgressHUD.showErrorWithStatus("加载微博数据失败，网络不给力", maskType: SVProgressHUDMaskType.Black)
                
                return
            }
            
            if since_id > 0 {
                
                let count = statuses?.count ?? 0
                self.showTipView(count)
                
            }
            if statuses == nil || statuses?.count == 0{
                SVProgressHUD.showErrorWithStatus("没有新的微博数据", maskType: SVProgressHUDMaskType.Black)
                return
            }
            
            if since_id > 0{
                
                print("下拉刷新，获取到：\(statuses?.count)")
                self.statuses = statuses! + self.statuses!
            }else if max_id > 0 {
                
                print("上拉加载更多数据，获取到：\(statuses?.count)")
                self.statuses = self.statuses! + statuses!
            }else{
                
                self.statuses = statuses
                print("获取最新20条数据.获取到 \(statuses?.count) 条微博")
            }
            
        }
        
    }
    
    private func showTipView(count: Int){
        
        let tipLabelHeight:CGFloat = 44
        let tipLabel = UILabel()
        tipLabel.frame = CGRect(x: 0, y: -20 - tipLabelHeight, width:UIScreen.mainScreen().bounds.width, height: tipLabelHeight)
        
        tipLabel.textColor = UIColor.whiteColor()
        tipLabel.backgroundColor = UIColor.orangeColor()
        tipLabel.font = UIFont.systemFontOfSize(16)
        tipLabel.textAlignment = NSTextAlignment.Center
        
        tipLabel.text = count == 0 ? "没有新的微博" :"加载了\(count)条微博"
        
        navigationController?.navigationBar.insertSubview(tipLabel, atIndex: 0)
        
        let duration = 0.75
        
        UIView.animateWithDuration(duration, animations: { () -> Void in
            // 让动画反过来执行
            //            UIView.setAnimationRepeatAutoreverses(true)
            
            // 重复执行
            //            UIView.setAnimationRepeatCount(5)
            tipLabel.frame.origin.y = tipLabelHeight
            }) { (_) -> Void in
                
                UIView.animateWithDuration(duration, delay: 0.3, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in
                    tipLabel.frame.origin.y = -20 - tipLabelHeight
                    }, completion: { (_) -> Void in
                        tipLabel.removeFromSuperview()
                })
        }
    }
    
   private func prepareTableView(){
        
        tableView.tableFooterView = pullUpView
        
        tableView.registerClass(LLstatusNormalCell.self, forCellReuseIdentifier: LLStatusCellIdentifier.NormalCell.rawValue)
        
        tableView.registerClass(LLStatusForwardCell.self, forCellReuseIdentifier: LLStatusCellIdentifier.ForwardCell.rawValue)
        
        
        refreshControl = LLRefreshControl()
        
        refreshControl?.addTarget(self, action: "loadData", forControlEvents: UIControlEvents.ValueChanged)
        
        refreshControl?.beginRefreshing()
        
        refreshControl?.sendActionsForControlEvents(UIControlEvents.ValueChanged)

        //        tableView.rowHeight = 200
        //        tableView.estimatedRowHeight = 300
        
        //        tableView.rowHeight = 400
    }
    
    private func setUpNavgationBar(){
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendsearch")
        navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop")
        let name = LLUserAccount.loadAccount()?.name ?? "没有名称"
        // 设置title
        let button = LLHomeTitleView()
        button.setTitle(name, forState: UIControlState.Normal)
        
        button.setImage(UIImage(named: "navigationbar_arrow_down"), forState: UIControlState.Normal)
        button.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
        button.sizeToFit()
        
        //Mark 方法名有参数要加冒号
        button.addTarget(self, action: "homeTitleClick:", forControlEvents: UIControlEvents.TouchUpInside)
        navigationItem.titleView = button
    }
    
    
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        let status = statuses![indexPath.row]
        //模型里取行高
        if let rowHeight = status.rowHerght{
            //            print("-----------------------------返回cell: \(indexPath.row), 缓存的行高:\(rowHeight)")
            //有则返回
            return rowHeight
        }
        let id = status.cellID()
        
        let cell = tableView.dequeueReusableCellWithIdentifier(id)as!LLStatusCell
        //没有则计算
        let rowHeight = cell.rowHeight(status)
        
        //        print("计算: \(indexPath.row), cell高度: \(rowHeight)")
        //缓存行高
        status.rowHerght = rowHeight
        
        return rowHeight
    }
    
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return statuses?.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let status = statuses![indexPath.row]
        
        let cell = tableView.dequeueReusableCellWithIdentifier(status.cellID())as!LLStatusCell
        
        cell.status = status
        
        cell.CellDelegate = self
        
        if indexPath.row == statuses!.count - 1 && !pullUpView.isAnimating(){
            
            pullUpView.startAnimating()
            
            loadData()
        }
        
        return cell
    }
    
    
    private lazy var pullUpView: UIActivityIndicatorView = {
        
        let indicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
        
        indicator.color = UIColor.magentaColor()
        
        return indicator
        }()
}


extension LLHomeViewController:LLStatusCellDelegate{

    func urlClick(text: String) {
        
        let homeWebViewVC = LLHomeWebViewController()
        
        homeWebViewVC.url = NSURL(string: text)
        //隐藏底部bar
        homeWebViewVC.hidesBottomBarWhenPushed = true
        
        navigationController?.pushViewController(homeWebViewVC, animated: true)
    }
}

extension LLHomeViewController:UIViewControllerTransitioningDelegate{
    
    @objc private func homeTitleClick(button:UIButton){
        button.selected = !button.selected
        // UIView动画,就近. 270 = 360 - 90，就近转90
        //            // 当两边一样远的时候顺时针.
        var transform: CGAffineTransform?
        if button.selected {
            transform = CGAffineTransformMakeRotation(CGFloat(M_PI - 0.01))
        } else {
            transform = CGAffineTransformIdentity
        }
        
        UIView.animateWithDuration(0.25) { () -> Void in
            button.imageView?.transform = transform!
        }
        
        if button.selected {
            
            let popoverSB = UIStoryboard(name: "PopoViewStoryboard", bundle: nil)
            
            let popoverVC = popoverSB.instantiateViewControllerWithIdentifier("popoVerController")
            
            popoverVC.transitioningDelegate = self
            
            popoverVC.modalPresentationStyle = UIModalPresentationStyle.Custom
            
            presentViewController(popoverVC, animated: true, completion: nil)
        }
        
    }
    //         返回一个 控制展现(显示) 的对象
    func presentationControllerForPresentedViewController(presented: UIViewController, presentingViewController presenting: UIViewController, sourceViewController source: UIViewController) -> UIPresentationController? {
        
        return LLPresentattionController(presentedViewController:presented,presentingViewController: presenting)
    }
    
    func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning?{
        
        return LLModalAnimation()
    }
    
    func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning?{
        
        return LLDismissAnimation()
    }

    
}
